########################################################################################
##  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING THIS SOFTWARE
##
##  By downloading, copying, installing or using the software you agree to this license.
##  If you do not agree to this license, do not download, install, copy or use the software.
##
## Copyright (C) 2013, AerVision Technologies Pty Ltd, all rights reserved.
##
## Redistribution and use in source and binary forms, with or without modification,
## are permitted provided that the following conditions are met:
##
##   * Redistribution's of source code must retain the above copyright notice,
##     this list of conditions and the following disclaimer.
##
##   * Redistribution's in binary form must reproduce the above copyright notice,
##     this list of conditions and the following disclaimer in the documentation
##     and/or other materials provided with the distribution.
##
##   * The name of AerVision Technologies, may not be used to endorse or promote products
##     derived from this software without specific prior written permission.
##
## This software is provided by the copyright holders and contributors to demonstrate 
## www.AerCloud.net Framework as a Service API (FaaS), "as is" and
## any express or implied warranties, including, but not limited to, the implied
## warranties of merchantability and fitness for a particular purpose are disclaimed.
## In no event shall the copyright holder or contributors be liable for any direct,
## indirect, incidental, special, exemplary, or consequential damages
## (including, but not limited to, procurement of substitute goods or services;
## loss of use, data, or profits; or business interruption) however caused
## and on any theory of liability, whether in contract, strict liability,
## or tort (including negligence or otherwise) arising in any way out of
## the use of this software, even if advised of the possibility of such damage.
########################################################################################

import thread
import logging

from Tkinter import Frame, Label

from aercloudclient.utils.AerCloudNet_Interface import AerCloudNet_Interface
from aercloudclient.gui.widgets import ScrolledFrame
from aercloudclient.utils.ImageLoader import ImageLoader

class LoadingFrame(Frame):
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)            
        Label(self, text="Searching...", font=("Helvetica", 30)).pack(fill='both', expand=1)
        
class BrowseSearchResultsWindow:

    def __init__(self, master, controller, imageName, imageData):
        master.protocol('WM_DELETE_WINDOW', self.close_windows)
        master.wm_title("AerCloud.net Demo - Search Browser")
        master.minsize(420, 400)
        self.master = master
        self.controller = controller
        self.main_frame = Frame(self.master)
        self.main_frame.pack(fill='both', expand=1)
        self.main_frame.grid_rowconfigure(0, weight=1)
        self.main_frame.grid_columnconfigure(0, weight=1)
        self.sframe = None
        self.loading_frame = LoadingFrame(self.main_frame)
        self.loading_frame.grid(row=0, column=0, sticky="nsew")
        self.image = []
        self.RefreshData(imageName, imageData)
    
    def loading(self):
        self.loading_frame.tkraise()
       
    def RefreshView(self, results, imageData):
        row = 1
        if len(results) == 0:
                Label(self.frame, text="No face found").grid(row=row, column=0)
                lbl = Label(self.frame, text="")
                lbl.grid(row=row, column=1)
                imageFrame = Frame(self.frame)
                imageFrame.grid(row=row, column=2, sticky='we')
                lbl = Label(imageFrame, text="")
                lbl.pack(side='left', anchor='w')
                imageFrame = Frame(self.frame, background='white')
                imageFrame.grid(row=row, column=3, sticky='we')            
                img = imageData.asThumbnail()
                self.image.append(img)
                lbl = Label(imageFrame, image=self.image[-1])
                lbl.pack(side='left', anchor='w')
                lbl.image = self.image[-1]        
        else:
            for r in results:
                Label(self.frame, text=r.name + "\n" + r.image_name).grid(row=row, column=0)
                lbl = Label(self.frame, text="%%%0.2f" % (r.match_score))
                lbl.grid(row=row, column=1)
                imageFrame = Frame(self.frame, background='white')
                imageFrame.grid(row=row, column=2, sticky='we')
                lbl = Label(imageFrame, text="")
                lbl.pack(side='left', anchor='w')
                img = ImageLoader(lbl, r.name, r.image_name)
                self.image.append(img)
                imageFrame = Frame(self.frame, background='white')
                imageFrame.grid(row=row, column=3, sticky='we')            
                img = imageData.asThumbnail()
                self.image.append(img)
                lbl = Label(imageFrame, image=self.image[-1])
                lbl.pack(side='left', anchor='w')
                lbl.image = self.image[-1]
                row += 1
        
    def RefreshAction(self, imageName, imageData):
        try:
            results = AerCloudNet_Interface.SearchFace(imageName, imageData)
            self.main_frame.after(0, self.sframe.tkraise)
            thread.start_new_thread(self.RefreshView, (results, imageData))            
        except Exception as ex:
            logging.error(str(ex))
            self.close_window()
        
    def RefreshData(self, imageName, imageData):
        self.main_frame.after(0, self.loading)
        if self.sframe != None:
            self.frame.destroy()
            self.sframe.destroy()
        self.sframe = ScrolledFrame(self.main_frame)
        self.sframe.grid(row=0, column=0, sticky="nsew")
        self.frame = Frame(self.sframe.interior)
        self.frame.pack(fill='both', expand=1)
        self.frame.grid_columnconfigure(0, minsize=200, weight=2)
        self.frame.grid_columnconfigure(1, minsize=100, weight=2)
        self.frame.grid_columnconfigure(2, minsize=100, weight=2)
        self.frame.grid_columnconfigure(3, minsize=100, weight=2)
        Label(self.frame, text="Text", relief='raised').grid(row=0, column=0, sticky='we')
        Label(self.frame, text="Similarity %", relief='raised').grid(row=0, column=1, sticky='we')
        Label(self.frame, text="Database Image", relief='raised').grid(row=0, column=2, sticky='we')
        Label(self.frame, text="Query Image", relief='raised').grid(row=0, column=3, sticky='we')
        thread.start_new_thread(self.RefreshAction, (imageName, imageData, ))
        
    def close_windows(self):
        del self.controller.search_browser[self]
        self.master.destroy()
        